package leetcode.code1663;

import java.util.StringJoiner;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String getSmallestString(int n, int k) {
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 26; i++) {
			int size = this.size(n, k, i);
			char c = (char) (i - 1 + 'a');
//			for (int j = 0; j < size; j++) {
//				sb.append(c);
//			}
			sb.append(this.append(c, size));
			n -= size;
			k -= size * i;
		}
		return sb.toString();
	}

	public StringBuffer append(char c, int size) {
		StringBuffer sb = new StringBuffer();
		if (size == 0) {
			return sb;
		}
		if (size == 1) {
			return sb.append(c);
		}
		StringBuffer half = this.append(c, size >> 1);
		if ((size & 1) == 0) {
			return sb.append(half).append(half);
		}
		return sb.append(half).append(half).append(c);
	}

	private int size(int n, int k, int i) {
		int l = 0, r = n;
		int ans = 0;
		while (l <= r) {
			int m = ((r - l) >> 1) + l;
			if (26 * (n - m) >= k - m * i) {
				ans = m;
				l = m + 1;
			} else {
				r = m - 1;
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		H.compare("aay", this.getSmallestString(3, 27));
		H.compare("aaszz", this.getSmallestString(5, 73));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
